import {isTextFieldEntryEdited, SelectEntry, TextFieldEntry} from "@bpmn-io/properties-panel";
import {useService} from "bpmn-js-properties-panel";
import {getBusinessObject, is} from "bpmn-js/lib/util/ModelUtil";
import {getScriptProperty,getScriptType} from "../util"
const component = {
    id: 'scriptType',
    component: ScriptType,
    isEdited: isTextFieldEntryEdited
}

if(window['register']) {
    window['register'].regComponent(component.id,component)
}
export default function(element) {
    component['element']=element;
    return component;
}

function ScriptType(props) {
    const {
        element,
        idPrefix,
        script
    } = props;
    const commandStack = useService('commandStack');
    const translate = useService('translate');
    const businessObject = script || getBusinessObject(element);
    const scriptProperty = getScriptProperty(businessObject);
    const getValue = () => {
        return getScriptType(businessObject);
    };
    const setValue = value => {
        // reset script properties on type change
        const properties = {
            [scriptProperty]: value === 'script' ? '' : undefined,
            'activiti:resource': value === 'resource' ? '' : undefined
        };
        commandStack.execute('element.updateModdleProperties', {
            element,
            moddleElement: businessObject,
            properties
        });
    };
    const getOptions = () => {
        const options = [{
            value: '',
            label: translate('<none>')
        }, {
            value: 'resource',
            label: translate('External resource')
        }, {
            value: 'script',
            label: translate('Inline script')
        }];
        return options;
    };
    return SelectEntry({
        element,
        id: idPrefix + 'scriptType',
        label: translate('Type'),
        getValue,
        setValue,
        getOptions
    });
}
